/*******************以下代码实现sessionStorage数据共享 START***********************/
var waitCopySessionStorageFinish = false;
if (!sessionStorage.length) {
    // 这个调用能触发目标事件，从而达到共享数据的目的
    localStorage.setItem('getSessionStorage', Date.now());
}
window.addEventListener('storage', function(event) {
    if (event.key == 'getSessionStorage') {
        // 已存在的标签页会收到这个事件
        localStorage.setItem('sessionStorageData', JSON.stringify(sessionStorage));
        localStorage.removeItem('sessionStorageData');
    } else if (event.key == 'sessionStorageData' && !sessionStorage.length) {
        // 新开启的标签页会收到这个事件
        var data = JSON.parse(event.newValue),
             value;
        for (key in data) {
            sessionStorage.setItem(key, data[key]);
        }
        location.reload()
    }
});
/*******************以上代码实现sessionStorage数据共享 END***********************/

/**
 * 判断年份是否为润年
 *
 * @param {Number} year
 */
 function isLeapYear (year) {
    return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
/**
 * 获取某一年份的某一月份的天数
 *
 * @param {Number} year
 * @param {Number} month
 */
 function getMonthDays(year, month) {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (isLeapYear(year) ? 29 : 28);
}
 /**
 * 获取某年的某天是第几周
 * @param {Number} y
 * @param {Number} m
 * @param {Number} d
 * @returns {Number}
 */
function getWeekNumber(y, m, d) {
    var now = new Date(y, m - 1, d),
        year = now.getFullYear(),
        month = now.getMonth(),
        days = now.getDate();
    //那一天是那一年中的第多少天
    for (var i = 0; i < month; i++) {
        days += getMonthDays(year, i);
    }

    //那一年第一天是星期几
    var yearFirstDay = new Date(year, 0, 1).getDay() || 7;

    var week = null;
    if (yearFirstDay == 1) {
        week = Math.ceil(days / yearFirstDay);
    } else {
        days -= (7 - yearFirstDay + 1);
        week = Math.ceil(days / 7) + 1;
    }

    return week;
}

//深度克隆，防止对象共享内存地址
function deep_clone (obj) {
    var _tmp,result;
    _tmp = JSON.stringify(obj);
    result = JSON.parse(_tmp);
    return result;
}
/*
 * 判断是否为空
 */
// function is_empty( obj ){
//     if( typeof obj == "undefined"  ){
//         return true;
//     }else if( obj == null ){
//         return true;
//     }else if ( trim(obj.toString()) == "" ){
//         return true;
//     }else if( typeof(obj) == 'object' && ( Object.getOwnPropertyNames(obj).lenth === 0 || (Object.getOwnPropertyNames(obj).length === 1 && Object.getOwnPropertyNames(obj).indexOf('__ob__') > -1 )  ) ){
//        return true;
//     }else if( obj.lenth === 0 || (obj.length === 1 && obj.indexOf('__ob__') > -1 )){
//         return true;
//     }else{
//         return false;
//     }
//     function trim(str){
//         return str.replace(/(^\s*)|(\s*$)/g, "");
//     }
// }
function is_empty( obj ){
    if( typeof obj == "undefined" || obj == null || trim(obj.toString()) == "" || (typeof(obj) == 'object' && JSON.stringify(obj) == "{}") || obj.lenth === 0 ){ 
        return true;
    }else{
        return false;
    }
    function trim(str){
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }
}

function in_array(ele,arr,inx = null){
    for(i=0;i<arr.length;i++) { 
        if( is_empty(inx) ){
            if(arr[i] == ele){
                return true; 

            }
        }else{
            if( arr[i][inx] == ele ){
                return true; 
            }
        }
       
    } 
     return false
}
//提取二维数组中某一列的值
function getOneColumn( arrrr , filed ){
    if( is_empty( arrrr ) ){
        return [];
    }
    if( !arrrr[0].hasOwnProperty(filed) || is_empty(arrrr) || is_empty(filed) ){
        return [];
    } 
    var re_arr = [];
    for (var i = 0; i < arrrr.length; i++) {
       re_arr.push(arrrr[i][filed])
    }
    return re_arr;
}

//时间戳转日期
function timestampToTime( timestamp = null ) {
    if( typeof(timestamp) == 'number' ){
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    }else if(typeof(timestamp) == 'object' && !is_empty(timestamp) ){
        var date = new Date(timestamp);//标准日期格式
    }else{
        var date = new Date();
    }
   
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = (date.getDate() < 10 ? '0'+ date.getDate() : date.getDate()) + ' ' ;
    h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':';
    m = (date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes()) + ':';
    s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
    return Y+M+D+h+m+s;
}
/**
 * 格式化秒数
 * @return Array
 */
function formatSeconds( value ) {
    var second = parseInt( value ); // 秒
    var minute = 0; // 分
    var hour = 0; // 小时
    var result = [];
    if ( second > 60 ) {
        minute = parseInt( second / 60 );
        second = parseInt( second % 60 );
        if ( minute > 60 ) {
            hour = parseInt( minute / 60 );
            minute = parseInt( minute % 60 );
        }
    }
    result[ 'second' ] = str_pad_left( parseInt( second ).toString(), 2, '0' );
    result[ 'minute' ] = str_pad_left( parseInt( minute ).toString(), 2, '0' );
    result[ 'hour' ] = str_pad_left( parseInt( hour ).toString(), 2, '0' );
    return result;
}

function str_pad_left( str, width, pad_char ) {
    return str.length < width ? str_pad_left( pad_char + str, width, pad_char ) : str;
}

/**
 * 将秒数换成时分秒格式
 * 作者：龙周峰
 */
function formatSecondsToHour(val) {
    var h = Math.floor(val / 3600),
        m = Math.floor((val / 60 % 60)),
        s = Math.floor((val % 60));
    if(h < 10){
        h = '0'+h;
    }
    if(m < 10){
        m = '0'+m;
    }
    if(s < 10){
        s = '0'+s;
    }
    return h + ":" + m + ":" + s ;
}

/*检测值是否为空*/
function checkSpace(val) {
    if (val && !Number.isInteger(val)) {
        return val.trim() ? val : '';
    }
    return val;
}

function restrictFn(fn, delay, isDebounce){
	let timer
	let lastCall = 0
	return function (...args) {
	  if (isDebounce) {
	    if (timer) clearTimeout(timer)
	    timer = setTimeout(() => {
	      fn(...args)
	    }, delay)
	  } else {
	    const now = new Date().getTime()
	    if (now - lastCall < delay) return
	    lastCall = now
	    fn(...args)
	  }
	}
}

function getDateTimeStamp (dateStr) {
    return Date.parse(dateStr.replace(/-/gi,"/"));
}

function getDateDiff (dateStr) {
    var publishTime = getDateTimeStamp(dateStr)/1000,
        d_seconds,
        d_minutes,
        d_hours,
        d_days,
        timeNow = parseInt(new Date().getTime()/1000),
        d,

        date = new Date(publishTime*1000),
        Y = date.getFullYear(),
        M = date.getMonth() + 1,
        D = date.getDate(),
        H = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds();
        //小于10的在前面补0
        if (M < 10) {
            M = '0' + M;
        }
        if (D < 10) {
            D = '0' + D;
        }
        if (H < 10) {
            H = '0' + H;
        }
        if (m < 10) {
            m = '0' + m;
        }
        if (s < 10) {
            s = '0' + s;
        }

    d = timeNow - publishTime;
    d_days = parseInt(d/86400);
    d_hours = parseInt(d/3600);
    d_minutes = parseInt(d/60);
    d_seconds = parseInt(d);

    if(d_days > 0 && d_days < 3){
        return d_days + '天前';
    }else if(d_days <= 0 && d_hours > 0){
        return d_hours + '小时前';
    }else if(d_hours <= 0 && d_minutes > 0){
        return d_minutes + '分钟前';
    }else if (d_seconds < 60) {
        if (d_seconds <= 0) {
            return '刚刚发表';
        }else {
            return d_seconds + '秒前';
        }
    }else if (d_days >= 3 && d_days < 30){
        return M + '-' + D + ' ' + H + ':' + m;
    }else if (d_days >= 30) {
        // return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
        return M + '-' + D + ' ' + H + ':' + m;
    }
}


//字符编码数值对应的存储长度：     
//UCS-2编码(16进制) UTF-8 字节流(二进制)    
//0000 - 007F       0xxxxxxx （1字节）     
//0080 - 07FF       110xxxxx 10xxxxxx （2字节）     
//0800 - FFFF       1110xxxx 10xxxxxx 10xxxxxx （3字节）  
String.prototype.getBytesLength = function() {   
    var totalLength = 0;     
    var charCode;  
    for (var i = 0; i < this.length; i++) {  
        charCode = this.charCodeAt(i);  
        if (charCode < 0x007f)  {     
            totalLength++;     
        } else if ((0x0080 <= charCode) && (charCode <= 0x07ff))  {     
            totalLength += 2;     
        } else if ((0x0800 <= charCode) && (charCode <= 0xffff))  {     
            totalLength += 3;   
        } else{  
            totalLength += 4;   
        }          
    }  
    return totalLength;   
} 
/**
* 处理接口规范的数据兼容旧版本
* @param {Object} data 
*/
function handleResponseData( data, need ){
  if (need === 'need') {
    var responseData = deep_clone( data.data );
        responseData.code = data.return;
        responseData.msg = data.return_message;
        return responseData;
    }else{
       return data 
    }
}

